package de.scs.core;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;

import javax.accessibility.AccessibleContext;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import javax.swing.UIManager;

import de.scs.ui.InsulinPumpMonitor;

public class DataProgress implements PropertyChangeListener
{

  private ProgressMonitor    progressMonitor;
  private Task               task;
  private InsulinPumpMonitor insulinPumpMonitor;

  class Task extends SwingWorker<Void, Void>
  {
    @Override
    public Void doInBackground()
    {
      Random random = new Random();
      int progress = 0;
      setProgress(0);
      try
      {
        while (progress < 100 && !isCancelled())
        {
          Thread.sleep(random.nextInt(1000));
          progress += random.nextInt(20);
          setProgress(Math.min(progress, 100));
        }
      }
      catch (InterruptedException ignore)
      {
      }
      return null;
    }

    @Override
    public void done()
    {
    }
  }

  public DataProgress(InsulinPumpMonitor insulinPumpMonitor)
  {
    this.insulinPumpMonitor = insulinPumpMonitor;
  }

  public void generateProgress()
  {
    UIManager.put("ProgressMonitor.progressText", "Progress");
    UIManager.put("OptionPane.cancelButtonText", "Cancel");
    progressMonitor = new ProgressMonitor(insulinPumpMonitor, "RECEIVING DATA", "", 0, 100);
    progressMonitor.setProgress(0);
    task = new Task();
    task.addPropertyChangeListener(this);
    task.execute();
  }

  public void propertyChange(PropertyChangeEvent evt)
  {
    if ("progress" == evt.getPropertyName())
    {
      int progress = (Integer) evt.getNewValue();
      progressMonitor.setProgress(progress);
      AccessibleContext ac = progressMonitor.getAccessibleContext();
      JDialog dialog = (JDialog) ac.getAccessibleParent();
      java.util.List<JButton> components = null;
      java.util.List<JLabel> components2 = null;
      try
      {
        components = SwingUtils.getDescendantsOfType(JButton.class, dialog, true);
        JButton button = components.get(0);
        button.setVisible(false);
        components2 = SwingUtils.getDescendantsOfType(JLabel.class,dialog,true);
        JLabel label = components2.get(2);
        label.setIcon(null);
      }
      catch (Exception e)
      {
      }
      String message = String.format("Completed %d%%.\n", progress);
      progressMonitor.setNote(message);
      if (progressMonitor.isCanceled() || task.isDone()) if (progressMonitor.isCanceled()) task.cancel(true);
    }
  }
}